package com.gientecher.register.service;

import com.alibaba.fastjson.JSON;
import com.gientecher.register.entity.ClientEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class RegisterService {

    private final static String SERVICES_KEY = "SERVICE_LIST";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    public void doRegister(ClientEntity clientEntity) {
        String json = JSON.toJSONString(clientEntity);
        redisTemplate.opsForHash().put(SERVICES_KEY,clientEntity.getServiceName(),json);
    }

    public List<ClientEntity> getServices() {
        List<String> clients = redisTemplate.opsForHash().values(SERVICES_KEY);
        List<ClientEntity> entities = new ArrayList<>(clients.size());
        clients.forEach(x->{
            ClientEntity entity = JSON.parseObject(x,ClientEntity.class);
            entities.add(entity);
        });
        return entities;
    }

    public void checkServices() {
        List<ClientEntity> clients = getServices();
        clients.forEach(x->{
            //校验服务是否可用，不可用剔除列表
            System.out.println(x.getHealthCheckUrl());
            String result = restTemplate.getForObject(x.getHealthCheckUrl(),String.class);
            System.out.println(result);
        });
    }
}
